/*
 * Copyright 2021 Red Hat, Inc. and/or its affiliates.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.drools.workbench.screens.guided.dtable.backend.server.conversion.util;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;

import org.drools.workbench.models.datamodel.rule.BaseSingleFieldConstraint;
import org.drools.workbench.models.datamodel.rule.CompositeFieldConstraint;
import org.drools.workbench.models.datamodel.rule.FactPattern;
import org.drools.workbench.models.datamodel.rule.FieldConstraint;
import org.drools.workbench.models.datamodel.rule.IPattern;
import org.drools.workbench.models.datamodel.rule.SingleFieldConstraint;

public class ConstraintVisitor {

    private final List<String> result = new ArrayList<>();

    private final IPattern iPattern;
    private final Map<IPattern, List<String>> conditionVariablesByDefinition;

    private final VariableOperators variableOperators;

    public ConstraintVisitor(final IPattern iPattern,
                             final Map<IPattern, List<String>> conditionVariablesByDefinition,
                             final VariableOperators variableOperators) {

        this.iPattern = iPattern;
        this.conditionVariablesByDefinition = conditionVariablesByDefinition;
        this.variableOperators = variableOperators;
    }

    public Collection<? extends String> visit() {
        for (final FieldConstraint constraint : ((FactPattern) iPattern).getConstraintList().getConstraints()) {
            visit(constraint);
        }
        return result;
    }

    private void visit(final FieldConstraint constraint) {
        if (constraint instanceof SingleFieldConstraint && ((SingleFieldConstraint) constraint).getConstraintValueType() == BaseSingleFieldConstraint.TYPE_TEMPLATE) {
            final String variable = ((SingleFieldConstraint) constraint).getValue();
            result.add(variable);
            conditionVariablesByDefinition.get(iPattern).add(variable);

            variableOperators.append(variable, ((SingleFieldConstraint) constraint).getOperator());
        } else if (constraint instanceof CompositeFieldConstraint && ((CompositeFieldConstraint) constraint).getConstraints() != null) {
            for (final FieldConstraint fieldConstraint : ((CompositeFieldConstraint) constraint).getConstraints()) {
                visit(fieldConstraint);
            }
        }
    }
}
